package eiisan.util.common;

import eiisan.config.security.util.Matcher;
import eiisan.constant.errors.code.ErrorCode;
import eiisan.constant.errors.exception.ServiceException;
import eiisan.dao.result.user.UserDetail;
import eiisan.service.user.AuthorityService;
import eiisan.util.model.response.Result;
import eiisan.util.spring.ContextUtil;
import eiisan.util.spring.MVCUtil;
import org.springframework.context.annotation.DependsOn;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * 登录用户信息获取工具类
 */
@Component
@DependsOn("contextUtil")
public class UserUtil {


	private static AuthorityService authorityService;

	/**
	 * 获取当前用户信息,不能用于免验证URI中
	 */
	public static UserDetail get() {
		HttpServletRequest request = MVCUtil.request();
		if (!Matcher.needVerify(request.getRequestURI())) {
			throw new RuntimeException("不能在免验证URI中获取token信息!");
		}
		User userDetails = null;
		try {
			userDetails = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		} catch (Exception e) {
			throw new ServiceException(ErrorCode.UNAUTHORIZED_ERROR);
		}
		return get(userDetails.getUsername());
	}

	/**
	 * 根据用户id查询用户信息,UserDetail,功能同UserUtil.find(userId)
	 */
	public static UserDetail get(Long userId) {
		Result<UserDetail> result = authorityService.getUserDetail(userId);
		if (Result.isNotSuccess(result)) {
			return null;
		}
		return result.getData();
	}

	/**
	 * 根据用户名查询用户信息,UserDetail,功能同UserUtil.find(userName)
	 */
	public static UserDetail get(String userName) {
		Result<UserDetail> result = authorityService.getUserDetailByUsername(userName);
		if (Result.isNotSuccess(result)) {
			return null;
		}
		return result.getData();
	}

	/**
	 * 根据用户id查询用户信息,以Result形式返回,功能同UserUtil.get(userId)
	 */
	public static Result<UserDetail> find(Long userId) {
		return authorityService.getUserDetail(userId);
	}

	/**
	 * 根据用户名查询用户信息,以Result形式返回,功能同UserUtil.get(userName)
	 */
	public static Result<UserDetail> find(String userName) {
		return authorityService.getUserDetailByUsername(userName);
	}

	@PostConstruct
	private void init() {
		authorityService = ContextUtil.get(AuthorityService.class);
		Assert.notNull(authorityService, "authorityService must not be null");
	}

}
